//
//  SoundViewController.m
//  NineGroupProject
//
//  Created by dllo on 15/12/25.
//  Copyright © 2015年 lushan. All rights reserved.
//

#import "SoundViewController.h"
#import "Masonry.h"
#import "LSAppTools.h"
#import "SoundModel.h"
#import "SoundCell.h"
#import "SoundDetailViewController.h"
#import "SoundDetailModel.h"
#import "UIImageView+WebCache.h"

@interface SoundViewController ()<UITableViewDataSource, UITableViewDelegate>




@end

@implementation SoundViewController


-(void)viewWillAppear:(BOOL)animated{
    
    NSLog(@"%@", [[NSUserDefaults standardUserDefaults]objectForKey:@"play"]);
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"play"] isEqualToString:@"0"]) {
        [self.playerView.startButton setImage:[UIImage imageNamed:@"lh-bofang.png"] forState:UIControlStateNormal];
    }else if([[[NSUserDefaults standardUserDefaults]objectForKey:@"play"] isEqualToString:@"1"]){
        [self.playerView.startButton setImage:[UIImage imageNamed:@"lh-zanting.png"] forState:UIControlStateNormal];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectZero];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"倾听"];
    customLab.textAlignment = NSTextAlignmentCenter;
    customLab.font = [UIFont boldSystemFontOfSize:20];
    [customLab sizeToFit];
    self.navigationItem.titleView = customLab;

    self.playerView = [[PlayerView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 150 * HEI)];
    self.playerView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0];
    [self.view addSubview:self.playerView];
    [self.playerView.startButton addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];

    
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 150 * HEI, WIDTH, HEIGHT - 150 * HEI - 64 - 48) style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.view addSubview:self.myTableView];

    [self.myTableView registerClass:[SoundCell class] forCellReuseIdentifier:@"cell"];
    
    self.soundArray = [[NSMutableArray alloc] init];

    NSString *url = @"http://api2.pianke.me/ting/radio";
    NSString *body = @"auth=&client=1&deviceid=DC7311B8-4DFE-4BC2-99D9-565BF1215670&version=3.0.6";
    

    [LSAppTools postUrl:url body:body result:LHJSON requestStyle:LHRequestString headerFile:nil success:^(id result) {
        NSMutableDictionary *bigDic = [result objectForKey:@"data"];
        NSMutableArray *array = [bigDic objectForKey:@"alllist"];
        for (NSMutableDictionary *dic in array) {
            
            SoundModel *sound = [[SoundModel alloc] init];
            [sound setValuesForKeysWithDictionary:dic];
            [self.soundArray addObject:sound];
            
        }
        
        [self.myTableView reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];

    
    //播放器
    self.player = [[STKAudioPlayer alloc]initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} } ];
    
    //定时器
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
    
    //Slider方法
    [self.playerView.progressSlider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    
    //音量Slider方法
    [self.playerView.soundSlider addTarget:self action:@selector(sliderSound) forControlEvents:UIControlEventTouchUpInside];
    
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicid:) name:@"musicid" object:nil];
    
}

- (void)musicid:(NSNotification *)notification{
    //notification object获得发送消息传递过来的值
    self._id = [[notification object] tingid];
    self.playerView.musicLabel.text = [[notification object] title];
    [self.playerView.musicImage sd_setImageWithURL:(NSURL *)[[notification object]coverimg] placeholderImage:[UIImage imageNamed:@"holderImage.jpg"]];
    
    //调用请求数据方法
    [self requestData];
    
}

//进度条
-(void)sliderAction{
    //改变播放进度
    [self.player seekToTime:self.playerView.progressSlider.value];
}

//音量条方法
- (void)sliderSound{
    self.player.volume = self.playerView.soundSlider.value;
}

//计时器
-(void)timeAction:(NSTimer *)timer{
    
    self.playerView.soundSlider.value = self.player.volume;
    
    self.playerView.progressSlider.maximumValue = self.player.duration;//duration 音乐总时长
    self.playerView.progressSlider.value = self.player.progress; //当前播放时长
    
    NSInteger yetMin = (NSInteger)self.player.progress / 60;
    NSInteger yetSec = (NSInteger)self.player.progress % 60;
    NSInteger allMin = (NSInteger)(self.player.duration)/60;
    NSInteger allSec = (NSInteger)(self.player.duration)%60;
    //显示时间
    self.playerView.presentTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", yetMin, yetSec];
    self.playerView.allTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", allMin, allSec];
    
    if (self.player.progress == self.player.duration) {
        [self.player resume];
        [self.playerView.startButton setImage:[UIImage imageNamed:@"lh-bofang.png"] forState:UIControlStateNormal];
    }
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"play"] isEqualToString:@"0"]) {
        [self.playerView.startButton setImage:[UIImage imageNamed:@"lh-bofang.png"] forState:UIControlStateNormal];
    }else if([[[NSUserDefaults standardUserDefaults]objectForKey:@"play"] isEqualToString:@"1"]){
        [self.playerView.startButton setImage:[UIImage imageNamed:@"lh-zanting.png"] forState:UIControlStateNormal];
    }
}

//播放
- (void)startAction:(UIButton *)startAction{
    
    if (self._id == nil) {
        
        UIAlertController *alertCon = [UIAlertController alertControllerWithTitle:@"提示" message:@"还没有音乐哦,请在下方电台中选择音乐" preferredStyle:UIAlertControllerStyleAlert];
        
        
        [self presentViewController:alertCon animated:YES completion:^{

        }];
        
        UIAlertAction *alertActCn = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        [alertCon addAction:alertActCn];
        
        
    }else{
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"play"] isEqualToString:@"0"]) {
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"play"];
            [self.playerView.startButton setImage:[UIImage imageNamed:@"lh-zanting.png"] forState:UIControlStateNormal];
        }else if([[[NSUserDefaults standardUserDefaults]objectForKey:@"play"] isEqualToString:@"1"]){
            [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"play"];
            [self.playerView.startButton setImage:[UIImage imageNamed:@"lh-bofang.png"] forState:UIControlStateNormal];
        }
        
        if (self.player.state == STKAudioPlayerStatePaused) {
            NSLog(@"暂停");
            [self.player resume];
        }else if (self.player.state == STKAudioPlayerStatePlaying) {
            NSLog(@"播放");
            [self.player pause];
        }
    }
}

//请求数据
-(void)requestData{
    
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"play"];
    NSLog(@"=============%@", [[NSUserDefaults standardUserDefaults]objectForKey:@"play"]);
    NSString *urlStr = @"http://api2.pianke.me/ting/info";
    NSString *body = [NSString stringWithFormat: @"auth=&client=1&deviceid=9573086A-0F03-4529-818F-432267320CE8&tingid=%@&version=3.0.6",self._id];
    
    
    [LSAppTools postUrl:urlStr body:body result:LHJSON requestStyle:LHRequestString headerFile:nil success:^(id result) {
        
        NSMutableDictionary *bigDic = [result objectForKey:@"data"];
        
        //播放
        NSString *url = [[bigDic objectForKey:@"playInfo"]objectForKey:@"musicUrl"];
        [self.player playURL:[NSURL URLWithString:url]];
        
    } failure:^(NSError *error) {
        
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.soundArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return WIDTH / 5 + 20 * WID;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    SoundCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    SoundModel *sound = [self.soundArray objectAtIndex:indexPath.row];
    // 取消点击cell的效果
    cell.soundModel = sound;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //选中有置灰效果  离开自动取消
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SoundDetailViewController *soundDVC = [[SoundDetailViewController alloc] init];
    SoundModel *sound = [self.soundArray objectAtIndex:indexPath.row];
    soundDVC.titleNss = sound.title;
    soundDVC.soundid = sound.radioid;
    [self.navigationController pushViewController:soundDVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
